package com.yqg.protection.listenern;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yqg.protection.controller.dto.ImportUserDto;
import com.yqg.protection.entity.User;
import com.yqg.protection.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * projectName:manage
 * author:zxf
 * time:2023/11/16 12:35
 * description:
 */
@Component
public class UserListener extends AnalysisEventListener<ImportUserDto> {

    @Autowired
    UserMapper userMapper;

    @Override
    public void invoke(ImportUserDto importUserDto, AnalysisContext analysisContext) {
        User user = new User();
        BeanUtil.copyProperties(importUserDto, user, true);
        if (user.getPassword() == null) {
            user.setPassword(SecureUtil.md5("123456"));
        }
        if (user.getOrganization() == null) {
            user.setOrganization(1l);
            user.setIsAllClient("0");
            user.setClientIds(null);
        } else {
            if (user.getIsAllClient() == null) {
                user.setIsAllClient("0");
                user.setClientIds(null);
            } else {
                if (user.getClientIdsStr() != null && isListIntFormat(user.getClientIdsStr())) {
                    user.setClientIds(listIntFormat(user.getClientIdsStr()));
                }
            }
        }
        if (user.getSuperviLength() != null) {
            user.setSuperviLength(user.getSuperviLength() * 3600 * 1000);
        }
        user.setIsDelete(0);
        user.setIsOnline("1");
        user.setLastLoginTime(System.currentTimeMillis());
        userMapper.insert(user);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
    }

    public static boolean isListIntFormat(String str) {
        // 正则表达式匹配List<Integer>格式
        String listPattern = "\\[(\\s*-?\\d+\\s*,?\\s*)+\\]";
        if (!str.matches(listPattern)) {
            return false; // 格式不匹配
        } else {
            return true;
        }
    }

    public static List<Long> listIntFormat(String str) {
        // 尝试将分割的字符串转换为整数
        try {
            List<Long> longList = new ObjectMapper().readValue(str, List.class);
            return longList; // 格式匹配且内容有效
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
